<template>
  <n-spin :show="mainStore.pageLoading" class="invite-container">
    <div class="invite-content text-center">
      <n-h2>推广返礼</n-h2>
      <n-h4 class="xs:my-4 m:my-6 leading-7">
        邀请好友注册，注册成功后您将获得
        <n-text code class="bg-slate-600/10 dark:bg-white/20">3</n-text>
        天套餐时长，后续订阅套餐您将获得
        <n-text code class="bg-slate-600/10 dark:bg-white/20">7</n-text>
        天套餐时长。
      </n-h4>
      <n-button
        v-if="inviteState.isWxMiniProgram"
        class="h-[40px] mb-3"
        type="success"
        @click="inviteState.inviteModalShow = true"
      >
        立即分享邀请好友
      </n-button>
      <n-alert v-else class="my-invitation rounded-lg" title="我的邀请链接" type="default" :bordered="false">
        <template #icon>
          <n-icon :component="ShareSocialOutline" />
        </template>
        <n-input v-model:value="inviteState.inviteUrl" class="mt-2 mb-4 h-11 flex items-center" readonly />
        <div class="flex gap-4">
          <n-button size="large" type="success" secondary @click="copyText(inviteState.inviteUrl)">复制链接</n-button>
          <n-button v-if="isWeiXin()" size="large" type="primary" @click="seeQrcode">
            {{ inviteState.showQrcode ? '关闭' : '查看' }}推广码
          </n-button>
          <n-button v-else size="large" type="primary" @click="downQrcode">下载推广码</n-button>
        </div>
      </n-alert>
      <n-grid
        class="count-grid xs:mt-4 s:mt-5"
        x-gap="xs:16 s:20"
        y-gap="xs:16 s:20"
        cols="xs:3 s:3"
        responsive="screen"
      >
        <n-gi>
          <n-alert class="text-center" :show-icon="false" title="注册人数" :bordered="false">
            {{ inviteState.registerCount }}人
          </n-alert>
        </n-gi>
        <n-gi>
          <n-alert class="text-center" :show-icon="false" title="订阅人数" :bordered="false">
            {{ inviteState.payCount }}人
          </n-alert>
        </n-gi>
        <n-gi>
          <n-alert class="text-center" :show-icon="false" title="已得天数" :bordered="false">
            {{ inviteState.obtainDay }}天
          </n-alert>
        </n-gi>
      </n-grid>
      <div v-show="false" id="qrcode-invite" class="mt-6">
        <qrcode-vue
          class="border rounded my-0 mx-auto"
          :value="inviteState.inviteUrl"
          :margin="2"
          :size="240"
          level="L"
        />
      </div>
      <img
        v-show="inviteState.showQrcode"
        class="mt-6 mb-0 mx-auto rounded"
        :src="inviteState.imgBase64"
        width="240"
        height="240"
        alt="qrcode"
      />
      <n-h4 class="xs:my-4 m:my-6">我的邀请记录</n-h4>
      <n-data-table
        remote
        :bordered="false"
        :row-key="row => row.nickname"
        :columns="inviteState.columns"
        :data="inviteState.tableData"
        :pagination="pagination"
      >
        <template #empty>
          <n-empty description="暂无邀请用户" />
        </template>
      </n-data-table>
    </div>
  </n-spin>
  <n-modal class="invite-modal" to=".invite-container" :show="inviteState.inviteModalShow">
    <div class="p-5">
      <div class="pb-5">
        <div class="text-lg mb-1 text-white"><strong>1、点击右上角【...】</strong></div>
        <div class="text-lg text-white"><strong>2、转发给好友</strong></div>
      </div>
      <img :src="getImageUrl('invite', 'share', 'png')" alt="share" />
      <div class="text-center mt-12">
        <n-button type="primary" dashed @click="inviteState.inviteModalShow = false">我已知晓</n-button>
      </div>
    </div>
  </n-modal>
</template>

<script setup>
import { reactive, defineAsyncComponent } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore, useMainStore } from '@/store'
import { inviteData, inviteList } from '@api/inviteApi'
import { ShareSocialOutline } from '@vicons/ionicons5'
import { copyText, isWeiXin, isMiniProgram, getImageUrl, timeFormat } from '@/utils'

const QrcodeVue = defineAsyncComponent(() => import('qrcode.vue'))
const userStore = useUserStore()
const mainStore = useMainStore()
const router = useRouter()

const inviteState = reactive({
  inviteModalShow: false,
  isWxMiniProgram: false,
  registerCount: 0,
  payCount: 0,
  obtainDay: 0,
  showQrcode: false,
  inviteUrl: `${location.origin}?ref=${userStore.invite_id}`,
  imgBase64: '',
  columns: [
    {
      title: '用户昵称',
      key: 'nickname',
    },
    {
      title: '注册时间',
      key: 'create_at',
      render(row) {
        return timeFormat(row.create_at)
      },
    },
    {
      title: '注册奖励',
      key: 'day',
      render() {
        return '套餐3天'
      },
    },
  ],
  tableData: [],
})

isMiniProgram().then(bool => {
  inviteState.isWxMiniProgram = bool
})

const pagination = reactive({
  ...mainStore.pagination,
  onChange(page) {
    pagination.page = page
    getInviteData()
  },
  onUpdatePageSize(pageSize) {
    pagination.page = 1
    pagination.pageSize = pageSize
    getInviteData()
  },
})

const getInviteData = async () => {
  try {
    mainStore.setPageLoading(true)
    const res = await Promise.allSettled([
      inviteData(),
      inviteList({ page: pagination.page, limit: pagination.pageSize }),
    ])
    if (res.length > 0) {
      if (res[0].status === 'fulfilled' && res[0].value.statusCode === 200) {
        const { payCount, registerCount } = res[0].value.data
        inviteState.payCount = payCount
        inviteState.registerCount = registerCount
        inviteState.obtainDay = payCount * 7 + registerCount * 3
      }
      if (res[1].status === 'fulfilled' && res[1].value.statusCode === 200) {
        const { list, count } = res[1].value.data
        inviteState.tableData = list
        pagination.itemCount = count
      }
    }
  } finally {
    mainStore.setPageLoading(false)
  }
}

if (userStore.edition === 'plus') {
  getInviteData()
} else {
  router.replace('/')
}

const getQrcodeBase64 = () => {
  const canvas = document.getElementById('qrcode-invite').getElementsByTagName('canvas')
  const base64 = canvas[0].toDataURL('img/png')
  return base64
}

const seeQrcode = () => {
  inviteState.showQrcode = !inviteState.showQrcode
  inviteState.imgBase64 = inviteState.imgBase64 || getQrcodeBase64()
}

const downQrcode = () => {
  let a = document.createElement('a')
  a.href = getQrcodeBase64()
  a.download = '二维码'
  a.click()
  a.remove()
}
</script>

<style lang="less" scoped>
.invite-container {
  &:deep(.invite-content) {
    max-width: 848px;
    margin: 0 auto;

    .n-alert {
      box-shadow: 0 1px 2px 0 rgb(0 0 0 / 0.05);
    }

    .my-invitation {
      .n-alert-body {
        padding: 16px 16px 16px 44px;
      }
    }

    .count-grid {
      .n-alert {
        .n-alert-body {
          padding: 20px 8px;
        }
      }
    }
    .n-data-table {
      .n-data-table__pagination {
        margin-top: 20px;
        justify-content: center;
      }
    }
  }

  &:deep(.invite-modal) {
    height: 100%;
    width: 100%;
    position: fixed;
    background: rgba(0 0 0 / 0.6);
    padding-top: 10vh !important;
  }
}
</style>
